<template>
  <div id="onlineCommunicate" style="padding: 10px; margin-bottom: 50px">
    <el-row>
        <el-col class="chat-nav">
            <ul>
                <li></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-chat-round"></i></router-link></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-user-solid"></i></router-link></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-orange"></i></router-link></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-folder-opened"></i></router-link></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-mobile-phone"></i></router-link></li>
                <li><router-link to="/#" class="chat"><i class="el-icon-menu"></i></router-link></li>
            </ul>
        </el-col>
      <el-col style="width: 280px;" >
        <el-card style="width: 100%; height: 580px; color: #333">
          <div style="padding-bottom: 10px; height:50px;line-height:50px;">
              <p class="chat-pic"><i class="el-icon-search"></i></p>
              <input type="search" class="chat-search" placeholder="搜索" v-model="getByEmpName" />
              <p class="chat-add"><i class="el-icon-plus"></i></p>
          </div>
          <div class="chat-list">
              <div
            style="padding: 10px 0;"
            v-for="user in users"
            :key="user.username"
          >
            <span>{{ user.username }}</span>
            <i
              class="el-icon-chat-dot-round"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="chatUser = user.username"
            ></i>
            <span
              style="font-size: 12px; color: limegreen; margin-left: 5px"
              v-if="user.username === chatUser"
              >chatting...</span>
          </div>
          </div>
        </el-card>
      </el-col>


      <el-col style="width:300px;">
        <div
          style="
            width: 600px;
            margin: 0 auto;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 0 10px #ccc;
          "
        >
          <div style="text-align: left;margin-left:20px;font-size:20px;font-weight:bold; height:70px;line-height: 70px">
            {{ chatUser }}
          </div>
          <div
            style="height: 310px; overflow: auto; border-top: 1px solid #ccc"
            v-html="content"
          ></div>
          <div style="height: 200px">
            <textarea
              v-model="text"
              style="
                height: 140px;
                width: 100%;
                padding: 20px;
                border: none;
                border-top: 1px solid #ccc;
                border-bottom: 0px solid #ccc;
                outline: none;
              "
            ></textarea>
            <div style="text-align:center; background-color:green; width:50px; height:30px; border-radius:5px; line-height:30px; color:white; margin-left:520px;">
              <el-button @click="send" style="background-color:green; border:none; color:white;"
                >发送</el-button
              >
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// import request from "@/utils/request";
let socket;

export default {
    name: "OnlineCommunicate",
    data() {
      return {
          circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
          user: {},
          isCollapse: false,
          users: [],
          chatUser: '',
          text: "",
          messages: [],
          content: '',
          getByEmpName:'',

      };
    },
    created() {
      this.init()
    },
    methods: {
      send() {
        if (!this.chatUser) {
          this.$message({type: 'warning', message: "请选择聊天对象"})
          return;
        }
        if (!this.text) {
          this.$message({type: 'warning', message: "请输入内容"})
        } else {
          if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
          } else {
            console.log("您的浏览器支持WebSocket");
            // 组装待发送的消息 json
            // {"from": "zhang", "to": "admin", "text": "聊天文本"}
            let message = {from: this.user.username, to: this.chatUser, text: this.text}
            socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
            this.messages.push({user: this.user.username, text: this.text})
            // 构建消息内容，本人消息
            this.createContent(null, this.user.username, this.text)
            this.text = '';
          }
        }
      },
      createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
        let html
        // 当前用户消息
        if (nowUser != null) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
          html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
              "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
              "    <div class=\"tip left\">" + text + "</div>\n" +
              "  </div>\n" +
              "  <div class=\"el-col el-col-2\">\n" +
              "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
              "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
              "  </span>\n" +
              "  </div>\n" +
              "</div>";
        } else if (remoteUser != null) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
          html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
              "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
              "    <div class=\"tip left\">" + text + "</div>\n" +
              "  </div>\n" +
              "  <div class=\"el-col el-col-2\">\n" +
              "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
              "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
              "  </span>\n" +
              "  </div>\n" +
              "</div>";
        }
        console.log(text)
        console.log(html)
        console.log(text)
        this.content += html;
      },
      init() {
        this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
        // this.user = (Math.random().toString(36).slice(-8))
        console.log(this.user)
        // let username = this.user.username;
        let username = (Math.random().toString(36).slice(-8));
        console.log(username)
        let _this = this;
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
        //   let socketUrl = "ws://localhost:8081/imserver/" + username;
          let socketUrl = "ws://localhost:8081/imserver/" + username;
          if (socket != null) {
            socket.close();
            socket = null;
          }
          // 开启一个websocket服务
          socket = new WebSocket(socketUrl);
          //打开事件
          socket.onopen = function () {
            console.log("websocket已打开");
          };
          //  浏览器端收消息，获得从服务端发送过来的文本消息
          socket.onmessage = function (msg) {
            console.log("收到数据====" + msg.data)
            let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
            if (data.users) {  // 获取在线人员信息
              _this.users = data.users.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
            } else {
              // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
              //  // {"from": "zhang", "text": "hello"}
              if (data.from === _this.chatUser) {
                _this.messages.push(data)
                // 构建消息内容
                _this.createContent(data.from, null, data.text)
              }
            }
          };
          //关闭事件
          socket.onclose = function () {
            console.log("websocket已关闭");
          };
          //发生了错误事件
          socket.onerror = function () {
            console.log("websocket发生了错误");
          }
        }
      }
    }
  }
</script>

<style scoped>
*{
    margin: 0px;
    padding: 0px;
}
.chat-nav{
    width: 60px;
    height: 580px;
    border-radius: 5px;
    background-color: rgb(80, 80, 80);
}
.chat-nav ul{
    list-style: none;
    padding-top: 20px;
}
.chat-nav ul li .chat{
    width: 50px;
    height: 50px;
    line-height: 50px;
    margin-left: 15px;
    margin-top: 20px;
    text-align: center;
    font-size: 25px;
    color: rgb(172, 171, 171);
    /* background-color: brown; */
}
.chat-nav ul li .chat:hover{
    color: white;
}
.chat-nav ul li:nth-child(1){
    width: 40px;
    height: 40px;
    line-height: 40px;
    margin-left: 10px;
    background-image: url("/src/assets/header.png");
    background-repeat: no-repeat;
    background-size: cover;
}
.chat-nav ul li:nth-child(2){
    margin-top: 10px;
}
.chat-nav ul li:nth-child(3){
    margin-top: 10px;
}
.chat-nav ul li:nth-child(4){
    margin-top: 10px;
}
.chat-nav ul li:nth-child(5){
    margin-top: 170px;
}
.chat-nav ul li:nth-child(6){
    margin-top: 10px;
}
.chat-nav ul li:nth-child(7){
    margin-top: 10px;
}

.chat-pic{
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 5px 0px 0px 5px;
    background-color: rgb(219, 217, 217);
}
.chat-search{
    display: inline-block;
    height: 30px;
    line-height: 30px;
    width: 160px;
    border-radius: 0px 5px 5px 0px;
    background-color: rgb(219, 217, 217);
    border: none;
}
.chat-add{
    display: inline-block;
    width: 30px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 5px;
    margin-left: 10px;
    background-color: rgb(219, 217, 217);
}
.chat-list{
    width: 260px;
    height: 580px;
    line-height: 580px;
    background-color: rgb(238, 238, 238);
}
.tip {
    color: white;
    text-align: center;
    border-radius: 10px;
    font-family: sans-serif;
    padding: 10px;
    width:auto;
    display:inline-block !important;
    display:inline;
}
.right {
    background-color: deepskyblue;
}
.left {
    background-color: forestgreen;
}
</style>